"use client";

import React, { useState, useEffect,useCallback ,useContext} from "react";

import Link from "next/link";

import { usePathname,useRouter } from "next/navigation";

// import Eruda from 'eruda';
import {
  Home,
  Users,
  Calendar,
  Book,
  MapPin,
  User,
  Package,
  Menu,
  X,
} from "lucide-react";

import { TrackerContext } from "@/trackContext";
import { SessionProvider } from 'next-auth/react'


export const SuperAdminPath = ["/campuses", "/courses", "/courts"];
const LayoutClient = ({ children,menuLang,currentUser,wxConfig}) => {
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const pathname = usePathname();
  const router = useRouter();
  console.log("pathname", pathname);
  console.log("currentUser", currentUser)
   const toggleSidebar = () => setIsSidebarOpen(!isSidebarOpen);
  const checkUser = useCallback((user) => {
    if (user) {
      if(SuperAdminPath.includes(pathname)){
        router.replace("/dash");
      }
    }
  }, [pathname, router])

  useEffect(() => {
    checkUser(currentUser);
  }, [currentUser, checkUser]);

  const initializeWeChatConfig = useCallback(async () => {
    try {
      const currentUrl = window.location.href.split("#")[0];
      const response = await wxConfig(currentUrl);
      const { appId, timestamp, nonceStr, signature } = response;
      window.wx.config({
        debug: false,
        appId,
        timestamp,
        nonceStr,
        signature,
        jsApiList: [
          "chooseImage",
          "uploadImage",
          "downloadImage",
          "getBrandWCPayRequest",
          "updateAppMessageShareData",
          "updateTimelineShareData",
          "onMenuShareWeibo",
          "onMenuShareQZone",
          "menuItem:share:appMessage",
          "menuItem:share:timeline",
          "menuItem:favorite",
          "menuItem:share:QZone",
          "menuItem:share:weiboApp",
        ],
      });

      window.wx.ready(() => {
        console.log("微信JS-SDK初始化成功");
        // updateShareData();
      });

      window.wx.error((res) => {
        console.error("微信JS-SDK初始化失败:", res);
      });
    } catch (error) {
      console.error("获取微信配置参数失败:", error);
    }
  }, [wxConfig]);


  useEffect(() => {
    // 动态加载微信 JSSDK 脚本
    const script = document.createElement('script');
    script.src = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js';
    script.async = true;
    script.onload = () => {
      console.log('微信 JSSDK 加载完成');
      // 在此处调用初始化方法
      initializeWeChatConfig();
    };
    document.body.appendChild(script);

    return () => {
      // 组件卸载时移除脚本（可选）
      document.body.removeChild(script);
    };
  }, [initializeWeChatConfig]);



  const {initTracker, startTracking} = useContext(TrackerContext)

  useEffect( () => {
    if(process.env.NEXT_PUBLIC_IS_LOCAL === "true") {
      return;
    }
     initTracker()
     startTracking()
  }, [])



  const menuItems = [
    {
      name: menuLang.menu.profile,
      show: true,
      icon: User,
      href: "/profile",
    },
    {
      name: menuLang.menu.home,
      show: currentUser.role === "admin" || currentUser.role === "coach",
      icon: Home,
      href: "/appointment",
    },
    {
      name: menuLang.menu.campuses,
      show: currentUser.role === "admin" || currentUser.role === "coach",
      icon: MapPin,
      href: "/campuses",
    },
    {
      name: menuLang.menu.venues,
      show: currentUser.role === "admin",
      icon: MapPin,
      href: "/courts",
    },
    {
      name: menuLang.menu.coursePackages,
      show: currentUser.role === "admin" || currentUser.role === "coach",
      icon: Package,
      href: "/course-packages",
    },
    {
      name: menuLang.menu.reservations,
      show: currentUser.role === "admin",
      icon: Calendar,
      href: "/appointment-manager",
    },
    {
      name: menuLang.menu.users,
      show: currentUser.role === "admin",
      icon: Users,
      href: "/admin/users",
    },
    {
      name: menuLang.menu.courtBookingConfig,
      show: currentUser.role === "admin",
      icon: Calendar,
      href: "/court-booking-config",
    },
    {
      name: menuLang.menu.courtBooking,
      show: true,
      icon: Calendar,
      href: "/court-booking",
    },
  ];
  useEffect(() => {
    // import('eruda').then((eruda) => {
    //   eruda.default.init();
    // });
    setIsSidebarOpen(false);
  }, [pathname]);

  return (
    <SessionProvider basePath="/ty/api/auth">
      <div className="flex min-h-screen bg-gray-100">
        {/* Sidebar */}
        <aside
          className={`bg-white shadow-md w-64 fixed inset-y-0 left-0 transform ${
            isSidebarOpen ? "translate-x-0" : "-translate-x-full"
          } ${pathname.indexOf("/login")!=-1?"hidden":""} md:relative md:translate-x-0 transition duration-200 ease-in-out z-30`}
        >
          <div className="flex items-center justify-between p-4 border-b">
            <span className="text-xl font-semibold">半岛网球</span>
            <button onClick={toggleSidebar} className="md:hidden">
              <X size={24} />
            </button>
          </div>
          <nav className={`mt-5`}>
            {menuItems.map(
              (item) =>
                item.show && (
                  <Link key={item.name} href={item.href}>
                    <span
                      className={`flex items-center px-6 py-2 mt-4 duration-200 border-l-4 ${
                        pathname === item.href
                          ? "border-blue-500 text-blue-500"
                          : "border-transparent hover:bg-gray-100"
                      }`}
                    >
                      <div className="flex items-center">
                        <item.icon className="w-5 h-5" />
                      </div>
                      <span className="mx-4">{item.name}</span>
                    </span>
                  </Link>
                )
            )}
          </nav>
        </aside>

        {/* Main content */}
        <div className="flex-1 flex flex-col min-w-0">
          {/* Top bar */}
          <header className={`bg-white shadow-sm z-20 ${pathname.indexOf("/login") !== -1 ? "hidden" : ""}`}>
            <div className="max-w-7xl mx-auto py-4 px-4 sm:px-6 lg:px-8 md:hidden">
              <div className="flex items-center justify-between">
                <h2 className="font-semibold text-xl text-gray-800">
                {console.log('pathname',pathname.split('/')[2])}
                  {menuItems.find((item) => item.href.split('/')[1] === pathname.split('/')[2])?.name}
                </h2>
                <button onClick={toggleSidebar}>
                  <Menu size={24} />
                </button>
              </div>
            </div>
          </header>

          {/* Page content */}
          <main className={`flex-1 min-w-0 flex-shrink-0 overflow-x-hidden overflow-y-auto bg-gray-100 ${
            pathname.indexOf("/login") !== -1 ? "p-0" : ""
          }`}>
            <div className={`flex-1 min-w-0 flex-shrink-0 container mx-auto w-full max-w-full ${
              pathname.indexOf("/login") !== -1
                ? "p-0 max-w-none"
                : "px-4 sm:px-6 lg:px-8 py-8"
            }`}>
              {children}
            </div>
          </main>
        </div>

        {/* Overlay for mobile */}
        {isSidebarOpen && (
          <div
            className="fixed inset-0 bg-black opacity-50 z-20 md:hidden"
            onClick={toggleSidebar}
          ></div>
        )}
      </div>
    </SessionProvider>
  );
};

export default LayoutClient;
